package cmd

import (
	"cmd-tools/portscan"
	"github.com/fatih/color"
	"github.com/spf13/cobra"
)

var portScanCmd = &cobra.Command{
	Use:   "scanning",
	Short: "端口扫描",
	Long:  "网段端口扫描",
	Run: func(cmd *cobra.Command, args []string) {
		handler(cmd, args)

	},
}

func init() {
	portScanCmd.Flags().StringP("version", "v", "", "版本信息")
	portScanCmd.Flags().StringP("url", "u", "http://127.0.0.1", "扫描的地址")
	portScanCmd.Flags().StringP("port", "p", "22,80,3306,8080", "端口")
	portScanCmd.Flags().IntP("threads", "n", 100, "扫描的地址")
	portScanCmd.Flags().StringP("log", "l", "run.log", "保存的日志")
	rootCmd.AddCommand(portScanCmd)
}

// handler 具体处理
func handler(cmd *cobra.Command, args []string) {
	_, err := cmd.Flags().GetString("version")
	if err != nil {
		color.Cyan(`
                      __                                         
______   ____________/  |_            ______ ____ _____    ____  
\____ \ /  _ \_  __ \   __\  ______  /  ___// ___\\__  \  /    \ 
|  |_> >  <_> )  | \/|  |   /_____/  \___ \\  \___ / __ \|   |  \
|   __/ \____/|__|   |__|           /____  >\___  >____  /___|  /
|__|                                     \/     \/     \/     \/ 
-------------------------> 端口扫描:v0.1 <------------------------
		`)
	} else {
		params := parseArgs(cmd)
		params.Run()
	}

}

func parseArgs(cmd *cobra.Command) portscan.ScanParams {
	url, _ := cmd.Flags().GetString("url")
	port, _ := cmd.Flags().GetString("port")
	threads, _ := cmd.Flags().GetInt("threads")
	log, _ := cmd.Flags().GetString("log")
	return portscan.ScanParams{
		Ip:      url,
		Port:    port,
		Threads: threads,
		Log:     log,
	}
}
